<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/logo.png" class="logo" alt="logo">
        <h2>巨蜥云管理平台</h2>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <div 
          :class="['tab-item', loginType === 'account' ? 'active' : '']" 
          @click="loginType = 'account'"
        >
          账号密码登录
        </div>
        <div 
          :class="['tab-item', loginType === 'phone' ? 'active' : '']" 
          @click="loginType = 'phone'"
        >
          手机号登录
        </div>
      </div>
      
      <!-- 账号密码登录表单 -->
      <el-form
        v-if="loginType === 'account'"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item prop="verifyCode">
          <div class="verify-code-input">
            <el-input
              v-model="loginForm.result"
              placeholder="请输入验证码"
              :prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <img 
              class="verify-code-img" 
              :src="captchaImg" 
              @click="refreshCaptcha"
              alt="验证码"
            >
          </div>
        </el-form-item>
        
        <div class="login-options">
          <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
          <el-link type="primary">忘记密码？</el-link>
        </div>
        
        <el-button
          type="primary"
          class="login-button"
          :loading="loading"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form>

      <!-- 手机号登录表单 -->
      <el-form
        v-else
        ref="phoneFormRef"
        :model="phoneForm"
        :rules="phoneRules"
        class="login-form"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="phoneForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Phone"
          />
        </el-form-item>

        <el-form-item prop="smsCode">
          <div class="verify-code-input">
            <el-input
              v-model="phoneForm.smsCode"
              placeholder="请输入验证码"
              :prefix-icon="Message"
            />
            <el-button 
              class="send-code-btn"
              :disabled="countdown > 0"
              @click="sendSmsCode"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <div class="login-options">
          <el-checkbox v-model="phoneForm.remember">记住手机号</el-checkbox>
          <el-link type="primary">忘记密码？</el-link>
        </div>
        
        <el-button
          type="primary"
          class="login-button"
          :loading="loading"
          @click="handlePhoneLogin"
        >
          登录
        </el-button>
      </el-form>

      <!-- 第三方登录 -->
      <div class="third-party-login">
        <div class="divider">
          <span>其他登录方式</span>
        </div>
        <div class="login-icons">
          <div class="icon-item" @click="thirdPartyLogin('wechat')">
            <svg-icon icon-class="wechat" class="icon wechat" />
            <span>微信登录</span>
          </div>
          <div class="icon-item" @click="thirdPartyLogin('qq')">
            <svg-icon icon-class="qq" class="icon qq" />
            <span>QQ登录</span>
          </div>
          <div class="icon-item" @click="thirdPartyLogin('gitee')">
            <svg-icon icon-class="gitee" class="icon gitee" />
            <span>Gitee登录</span>
          </div>
          <div class="icon-item" @click="thirdPartyLogin('github')">
            <svg-icon icon-class="github" class="icon github" />
            <span>Github登录</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Message, Key } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { getCaptcha, login } from '@/api/auth'
import type { LoginDTO, LoginResult } from '@/types/auth'
import { throttle } from 'lodash-es'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()
const phoneFormRef = ref<FormInstance>()
const loading = ref(false)
const loginType = ref('account')
const countdown = ref(0)
const captchaImg = ref('')

const loginForm = ref<LoginDTO>({
  username: '',
  password: '',
  number: '',
  type: '2',
  code: '',
  result: '',
  remember: false
})

const phoneForm = reactive({
  phone: '',
  smsCode: '',
  remember: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await login(loginForm.value) as LoginResult
        if (res.code === 200) {
          const token = res.data
          localStorage.setItem('token', token)
          
          await userStore.setToken(token)
          
          // 获取用户信息和菜单
          const infoRes = await userStore.getInfo()
          console.log('登录后获取用户信息结果:', infoRes)
          console.log('当前 store 中的用户信息:', userStore.userInfo)
          console.log('当前 store 中的菜单列表:', userStore.menuList)
          
          if (!infoRes) {
            ElMessage.error('获取用户信息失败')
            userStore.clearToken()
            return
          }
          
          if (loginForm.value.remember) {
            localStorage.setItem('username', loginForm.value.username)
            localStorage.setItem('password', loginForm.value.password)
          } else {
            localStorage.removeItem('username')
            localStorage.removeItem('password')
          }
          
          ElMessage.success('登录成功')
          // 确保用户信息获取成功后再跳转
          router.push('/')
        } else {
          ElMessage.error(res.msg || '登录失败')
          refreshCaptcha()
          loginForm.value.result = ''
        }
      } catch (error: any) {
        console.error('登录失败:', error)
        refreshCaptcha()
        loginForm.value.result = ''
      } finally {
        loading.value = false
      }
    }
  })
}

const sendSmsCode = async () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  // 调用发送验证码接口
}

const handlePhoneLogin = async () => {
  if (!phoneFormRef.value) return
  
  await phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用手机号登录接口
        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        ElMessage.error('登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const thirdPartyLogin = (type: string) => {
  const loginUrls = {
    wechat: '/api/oauth2/authorization/wechat',
    qq: '/api/oauth2/authorization/qq',
    gitee: '/api/oauth2/authorization/gitee',
    github: '/api/oauth2/authorization/github'
  }
  
  window.location.href = loginUrls[type as keyof typeof loginUrls]
}

// 使用节流函数包装验证码刷新，2秒内只能刷新一次
const refreshCaptcha = throttle(async () => {
  try {
    const res = await getCaptcha()
    if (res.code === 200) {
      loginForm.value.code = res.msg
      captchaImg.value = res.data
      loginForm.value.result = ''
    } else {
      if (res.code === 429) {
        ElMessage.warning('请求过于频繁，请稍后再试')
      } else {
        ElMessage.error(res.msg || '获取验证码失败')
      }
    }
  } catch (error: any) {
    if (error.response?.status === 429) {
      ElMessage.warning('请求过于频繁，请稍后再试')
    } else {
      console.error('获取验证码失败:', error)
      ElMessage.error('获取验证码失败，请稍后重试')
    }
  }
}, 2000, { trailing: false })

onMounted(() => {
  refreshCaptcha()
  const rememberedUsername = localStorage.getItem('username')
  const rememberedPassword = localStorage.getItem('password')
  if (rememberedUsername && rememberedPassword) {
    loginForm.value.username = rememberedUsername
    loginForm.value.password = rememberedPassword
    loginForm.value.remember = true
  }
})
</script>

<style scoped lang="scss">
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .login-box {
    width: 420px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    animation: fadeIn 0.5s ease-out;
    
    .login-header {
      text-align: center;
      margin-bottom: 30px;
      
      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 16px;
        animation: logoRotate 20s linear infinite;
      }
      
      h2 {
        font-size: 28px;
        color: #303133;
        margin: 0;
        font-weight: 600;
        background: linear-gradient(to right, #667eea, #764ba2);
        -webkit-background-clip: text;
        color: transparent;
      }
    }

    .login-tabs {
      display: flex;
      margin-bottom: 30px;
      border-bottom: 2px solid #eee;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding: 12px 0;
        cursor: pointer;
        transition: all 0.3s;
        color: #606266;
        
        &.active {
          color: #667eea;
          border-bottom: 2px solid #667eea;
          transform: translateY(2px);
        }
        
        &:hover {
          color: #667eea;
        }
      }
    }
    
    .login-form {
      .verify-code-input {
        display: flex;
        gap: 10px;
        
        .verify-code-img {
          width: 100px;
          height: 40px;
          cursor: pointer;
          border-radius: 4px;
          vertical-align: middle;
          &:active {
            transform: scale(0.95);
          }
        }
        
        .send-code-btn {
          width: 120px;
        }
      }

      .login-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 20px 0;
      }
      
      .login-button {
        width: 100%;
        height: 44px;
        font-size: 16px;
        background: linear-gradient(to right, #667eea, #764ba2);
        border: none;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
      }
    }

    .third-party-login {
      margin-top: 30px;
      
      .divider {
        display: flex;
        align-items: center;
        color: #909399;
        margin: 20px 0;
        
        &::before,
        &::after {
          content: '';
          flex: 1;
          height: 1px;
          background: #dcdfe6;
          margin: 0 16px;
        }
      }
      
      .login-icons {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        gap: 20px;
        padding: 0 20px;
        
        .icon-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          cursor: pointer;
          transition: all 0.3s;
          
          .icon {
            font-size: 28px;
            margin-bottom: 8px;
            transition: all 0.3s;
            
            &.wechat {
              color: #07C160;
            }
            
            &.qq {
              color: #12B7F5;
            }
            
            &.gitee {
              color: #C71D23;
            }
            
            &.github {
              color: #24292F;
            }
          }
          
          span {
            font-size: 12px;
            color: #606266;
          }
          
          &:hover {
            transform: translateY(-2px);
            
            .icon {
              transform: scale(1.1);
            }
            
            span {
              color: #409EFF;
            }
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes logoRotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes iconPop {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.icon-item {
  &:hover .icon {
    animation: iconPop 0.3s ease-in-out;
  }
}
</style> 